<!--
 * @Author: lp 654528967@qq.com
 * @Date: 2022-06-13 09:47:11
 * @LastEditors: lp 654528967@qq.com
 * @LastEditTime: 2022-06-22 15:45:10
 * @FilePath: \nien-vue3-admin\src\views\resetPswd.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="reset-container">
    <div class="back-icon" @click="goLogin">
      <el-icon><Back /></el-icon>
    </div>
    <h2 class="title">{{ $t('layout.retrievePassword') }}</h2>
    <el-steps :active="stepActive" align-center>
      <el-step :title="$t('nameFormat.pleaseEnter',[$t('layout.accountNumber')])" />
      <el-step :title="$t('layout.authentication')" />
      <el-step :title="$t('layout.setupComplete')" />
    </el-steps>
              
    <el-form
      ref="resetFormRef"
      :model="resetForm"
      label-position="top"
      :rules="resetRules"
      :class="{'reset-m-t':stepActive===1?true:false}"
      @submit.prevent
    >
      <el-form-item v-if="stepActive===0" :label="$t('nameFormat.pleaseEnter',[$t('layout.yourUserAccount')])+'：'" prop="userName">
        <el-input v-model="resetForm.userName" :placeholder="$t('layout.pleaseEnterYourAccountOrJobNumber')" @keydown.enter="resetPswdNext" />
      </el-form-item>
                
      <template v-if="stepActive===1">
        <el-row class="reset-form-phone">
          <el-col>
            <span>{{ $t('public.phoneNumber') }}：{{ resetForm.phoneNumber }}</span>
          </el-col>
        </el-row>
        <el-form-item prop="code">
          <el-row style="width: 100%;">
            <el-col class="reset-code">
              <el-input v-model="resetForm.code" class="reset-code-input" :placeholder="$t('nameFormat.pleaseEnter',[$t('layout.verificationCode')])"></el-input>
              <el-button
                type="info"
                class="reset-code-button"
                :disabled="disabledCode"
                @click="handleMes"
              >
                {{ $t('layout.getVerificationCode') }}{{ disabledCode? `(${codeTimer})`:'' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="resetForm.password"
            type="password"
            show-password
            :placeholder="$t('nameFormat.pleaseEnter',[$t('layout.password')])"
          ></el-input>
        </el-form-item>
        <el-form-item prop="checkPassword">
          <el-input
            v-model="resetForm.checkPassword"
            type="password"
            show-password
            :placeholder="$t('layout.pleaseEnterTheNewPasswordAgain')"
            @keydown.enter="resetPswdNext"
          ></el-input>
        </el-form-item>
      </template>
      <template v-if="stepActive===3">
        <el-row>
          <el-col>
            <el-result
              icon="success"
              :title="$t('layout.yourPasswordHasBeenResetSuccessfully')"
            >
              <template #extra>
                <el-button type="primary" @click="goLogin">{{ $t('layout.returnToHomePage') }}</el-button>
                <p class="result-tip"><span>{{ autoLocationIndex }}</span> {{ $t('layout.afterSecondsGoHome') }}</p>
              </template>
            </el-result>
          </el-col>
          <el-col></el-col>
          <el-col></el-col>
        </el-row>
      </template>
 
      <el-form-item v-if="stepActive !==3">
        <el-button
          :loading="nextLoading"
          class="next-button"
          type="primary"
          @click="resetPswdNext"
        >
          {{ $t('public.nextStep') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang='ts' setup>
import { getCurrentInstance, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Back } from '@element-plus/icons-vue'
import { getPhone, getSms, updatePassword } from '@/api/user'
import { queryRedirect } from '@/utils'

const nextLoading = ref(false)
let codeIntervTimer = null
const router = useRouter()
const pswdValidator = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码！'))
  } else if (value !== resetForm.value.password) {
    callback(new Error('两次密码不一致！'))
  } else {
    callback()
  }
}
const { proxy: { $validateForm } }:any = getCurrentInstance()
const stepActive = ref(0), 
  codeTimer = ref(59),
  resetFormRef = ref(null),
  disabledCode = ref(false), 
  resetForm = ref({ userName: null, phoneNumber: null, code: null, password: null, checkPassword: null }), 
  resetRules = ref({
    userName: {
      required: true,
      message: '用户账户或者工号必填',
      trigger: 'blur',
    },
    code: {
      required: true,
      message: '验证码未输入',
      trigger: 'blur',
    },
    password: {
      required: true,
      message: '必须包括大小写字母，数字，特殊字符,长度为8-20位！',
      pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/,
      trigger: 'blur',
    },
    checkPassword: {
      trigger: 'blur',
      validator: pswdValidator,
    },
  }), 
  resetPswdNext = () => {
    $validateForm(resetFormRef.value, () => {
      if (stepActive.value === 1) {
        nextLoading.value = true
        updatePassword(resetForm.value).then(res => {
          if (res.code === 200) {
            stepActive.value += 2
            setInterval(autoLocationSetTime, 1000)
          }
        }).finally(() => {
          nextLoading.value = false
        })
      } else if (stepActive.value === 0) {
        nextLoading.value = true
        getPhone({ userName: resetForm.value.userName }).then(res => {
          if (res.code == 200) {
            resetForm.value.phoneNumber = res.data.phoneNumber
            stepActive.value++
          }
        }).finally(() => {
          nextLoading.value = false
        })
      } else {
        stepActive.value++
      }
    })
  }
const handleMes = () => {
  disabledCode.value = true
  codeIntervTimer = window.setInterval(() => {
    codeTimer.value--
    if (codeTimer.value === 0) {
      codeTimer.value = 59
      disabledCode.value = false
      clearInterval(codeIntervTimer)
    }
  }, 1000)
  getSms({
    phoneNumber: resetForm.value.phoneNumber,
  }).then(res => {
    console.log(res)
  })
}
const goLogin = () => {
  router.replace({ path: '/login/signIn', query: { redirect: queryRedirect().value } })
}
const autoLocationIndex = ref(10)
const autoLocationSetTime = () => {
  autoLocationIndex.value--
  if (autoLocationIndex.value === 0) {
    goLogin()
  }
}
</script>
<style lang='less' scoped>
@step-is-process:#010d19;
.reset-container {
  width: 256px;
  height: 100%;
  position: relative;
  .back-icon {
    position: absolute;
    top: 28px;
    left: -30px;
    font-size: 24px;
    cursor: pointer;
  }
  .next-button {
    width: 100%;
    margin-top: 6px;
  }
  .title {
    font-size: 16px;
    margin: 30px 0;
    /* stylelint-disable-next-line font-family-no-missing-generic-family-keyword */
    font-family: PingFangSC-Medium;
    font-weight: 600;
    text-align: center;
  }
  .reset-form-phone {
    margin-bottom: 10px;
  }
  .reset-m-t {
    margin-bottom: 24px;
  }
  .reset-code {
    display: flex;
    justify-content: space-between;
    .reset-code-input {
      width: 157px;
    }
    .reset-code-button {
      font-size: 12px;
      background-color: #f1f3f4;
      color: #010d19;
      width: 91px;
      &.is-disabled {
        span {
          opacity: 0.25;
        }
      }
    }
  }
  :deep(.el-steps) > {
    margin-left: -22px;
    width: 119%;
    .is-process {
      color: @step-is-process;
    }
    .el-step__head {
      .el-step__line {
        top: 7px;
        left: 47px;
        width: 90%;
        // color: #e3e6ed;
        border-color: #e3e6ed;
        border-style: dotted;
        border-top: 1px;
        background-color: transparent;
        transform: scale(0.65);
        .el-step__line-inner {
          display: none;
        }
      }
      .el-step__icon {
        width: 14px;
        height: 14px;
        .el-step__icon-inner {
          font-size: 12px;
          transform: scale(0.666);
        }
      }
      &.is-finish {
        .is-text {
          background-color: var(--el-color-primary);
        }
        .el-step__icon-inner {
          color: #fff;
        }
      }
    }
    .el-step__main {
      margin-bottom: 30px;
      .el-step__title {
        line-height: normal;
        &.is-finish {
          color: @step-is-process;
        }

        font-size: 12px;
        transform: scale(0.9166);
      }
    }
  }
}
</style>